{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "83c38079",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AI配置已加载，优先使用: 本地模型\n",
      "初始化教育AI模型：deepseek-r1:14b\n",
      "❌ 本地AI不可用 | ✅ 在线API可用\n",
      "🎓 教育助手系统启动中...\n",
      "🌐 访问地址: http://127.0.0.1:5000\n",
      "📱 功能包括：智能问答、作业批改、课程查询\n",
      " * Serving Flask app \"__main__\" (lazy loading)\n",
      " * Environment: production\n",
      "\u001b[31m   WARNING: This is a development server. Do not use it in a production deployment.\u001b[0m\n",
      "\u001b[2m   Use a production WSGI server instead.\u001b[0m\n",
      " * Debug mode: off\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      " * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n",
      "127.0.0.1 - - [28/May/2025 10:41:16] \"GET / HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [28/May/2025 10:41:16] \"GET /timetable HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [28/May/2025 10:41:16] \"GET /favicon.ico HTTP/1.1\" 404 -\n",
      "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ipykernel_3088\\320764180.py:1256: UserWarning: The 'environ['werkzeug.server.shutdown']' function is deprecated and will be removed in Werkzeug 2.1.\n",
      "  func()\n",
      "127.0.0.1 - - [28/May/2025 10:41:20] \"POST /shutdown HTTP/1.1\" 200 -\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🔄 如需重新启动，请重新运行代码\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "from flask import Flask, render_template, request, jsonify\n",
    "from datetime import datetime\n",
    "import os\n",
    "\n",
    "# ================== 模型管理模块 ==================\n",
    "class ModelManager:\n",
    "    def __init__(self):\n",
    "        self.loaded_models = {}\n",
    "        self.current_model = None\n",
    "        \n",
    "        # AI配置\n",
    "        self.config = {\n",
    "            'ollama_url': 'http://127.0.0.1:11434',\n",
    "            'ollama_model': 'deepseek-r1:14b',\n",
    "            'deepseek_api_key': 'sk-c1416715d38e4f66ab0c1e3ceb9c3d38',  # 您的API密钥\n",
    "            'deepseek_model': 'deepseek-chat',\n",
    "            'use_local_first': True,\n",
    "            'timeout': 120\n",
    "        }\n",
    "        \n",
    "        print(f\"AI配置已加载，优先使用: {'本地模型' if self.config['use_local_first'] else '在线API'}\")\n",
    "        \n",
    "    def load_model(self, model_name=None):\n",
    "        if model_name is None:\n",
    "            model_name = self.config['ollama_model']\n",
    "        print(f\"初始化教育AI模型：{model_name}\")\n",
    "        \n",
    "        # 检查本地AI可用性\n",
    "        local_available = self._check_local_ai()\n",
    "        online_available = self._check_online_api()\n",
    "        \n",
    "        status_info = []\n",
    "        if local_available:\n",
    "            status_info.append(\"✅ 本地AI可用\")\n",
    "        else:\n",
    "            status_info.append(\"❌ 本地AI不可用\")\n",
    "            \n",
    "        if online_available:\n",
    "            status_info.append(\"✅ 在线API可用\")\n",
    "        else:\n",
    "            status_info.append(\"❌ 在线API不可用\")\n",
    "        \n",
    "        print(\" | \".join(status_info))\n",
    "        \n",
    "        self.loaded_models[model_name] = {\n",
    "            \"status\": \"loaded\", \n",
    "            \"type\": \"educational_ai\",\n",
    "            \"local_available\": local_available,\n",
    "            \"online_available\": online_available\n",
    "        }\n",
    "        self.current_model = model_name\n",
    "        return \"ai_model\", \"ai_tokenizer\"\n",
    "\n",
    "    def _check_local_ai(self):\n",
    "        \"\"\"检查本地AI是否可用\"\"\"\n",
    "        try:\n",
    "            import requests\n",
    "            response = requests.get(f\"{self.config['ollama_url']}/api/tags\", timeout=5)\n",
    "            return response.status_code == 200\n",
    "        except:\n",
    "            return False\n",
    "\n",
    "    def _check_online_api(self):\n",
    "        \"\"\"检查DeepSeek在线API是否可用\"\"\"\n",
    "        try:\n",
    "            import requests\n",
    "            headers = {\n",
    "                'Authorization': f\"Bearer {self.config['deepseek_api_key']}\",\n",
    "                'Content-Type': 'application/json'\n",
    "            }\n",
    "            # 测试DeepSeek API连接 (使用模型列表接口)\n",
    "            response = requests.get('https://api.deepseek.com/v1/models', headers=headers, timeout=5)\n",
    "            return response.status_code == 200\n",
    "        except:\n",
    "            return False\n",
    "\n",
    "\n",
    "    def unload_model(self, model_name):\n",
    "        if model_name in self.loaded_models:\n",
    "            del self.loaded_models[model_name]\n",
    "            print(f\"卸载模型：{model_name}\")\n",
    "\n",
    "    def run_inference(self, input_text):\n",
    "        \"\"\"智能推理方法 - 优先本地AI，回退到在线API\"\"\"\n",
    "        if not input_text.strip():\n",
    "            return \"请输入您的问题，我会尽力帮助您！\"\n",
    "        \n",
    "        # 创建教育性提示词\n",
    "        prompt = self._create_educational_prompt(input_text)\n",
    "        \n",
    "        # 尝试本地AI\n",
    "        if self.config['use_local_first']:\n",
    "            try:\n",
    "                result = self._try_local_ai(prompt, input_text)\n",
    "                if result:\n",
    "                    return result\n",
    "            except Exception as e:\n",
    "                print(f\"本地AI调用失败: {e}\")\n",
    "        \n",
    "        # 回退到在线API\n",
    "        try:\n",
    "            result = self._try_online_api(prompt, input_text)\n",
    "            if result:\n",
    "                return result\n",
    "        except Exception as e:\n",
    "            print(f\"在线API调用失败: {e}\")\n",
    "        \n",
    "        # 最后回退到增强模拟回答\n",
    "        return self._generate_enhanced_fallback(input_text)\n",
    "\n",
    "    def _create_educational_prompt(self, question):\n",
    "        \"\"\"创建教育性提示词\"\"\"\n",
    "        return f\"\"\"你是一位专业的教育助手，请用适合中小学生理解的语言回答问题。\n",
    "\n",
    "    要求：\n",
    "    1. 回答要准确、详细且易懂\n",
    "    2. 适合中小学生的理解水平\n",
    "    3. 如果是数学题，请提供解题步骤\n",
    "    4. 如果是概念问题，请用简单的例子说明\n",
    "    5. 回答要有教育意义和启发性\n",
    "    6. 使用中文回答\n",
    "\n",
    "    学生问题：{question}\n",
    "\n",
    "    请提供详细的教育性回答：\"\"\"\n",
    "\n",
    "    def _try_local_ai(self, prompt, original_question):\n",
    "        \"\"\"尝试使用本地Ollama模型\"\"\"\n",
    "        try:\n",
    "            import requests\n",
    "            \n",
    "            print(f\"尝试本地AI: {self.config['ollama_model']}\")\n",
    "            data = {\n",
    "                'model': self.config['ollama_model'],\n",
    "                'prompt': prompt,\n",
    "                'stream': False,\n",
    "                'options': {\n",
    "                    'temperature': 0.7,\n",
    "                    'top_p': 0.9,\n",
    "                    'max_tokens': 500\n",
    "                }\n",
    "            }\n",
    "            \n",
    "            response = requests.post(\n",
    "                f\"{self.config['ollama_url']}/api/generate\",\n",
    "                json=data,\n",
    "                timeout=self.config['timeout']\n",
    "            )\n",
    "            \n",
    "            if response.status_code == 200:\n",
    "                result = response.json()\n",
    "                answer = result.get('response', '').strip()\n",
    "                if answer:\n",
    "                    print(\"✅ 本地AI调用成功\")\n",
    "                    return f\"🤖 本地AI回答：\\n\\n{answer}\"\n",
    "                else:\n",
    "                    print(\"⚠️ 本地AI返回空回答\")\n",
    "            else:\n",
    "                print(f\"❌ 本地AI调用失败，状态码: {response.status_code}, 响应: {response.text}\")\n",
    "                \n",
    "        except requests.exceptions.RequestException as e:\n",
    "            print(f\"本地AI网络请求异常: {e}\")\n",
    "        except Exception as e:\n",
    "            print(f\"本地AI调用未知异常: {e}\")\n",
    "        \n",
    "        return None\n",
    "\n",
    "    def _try_online_api(self, prompt, original_question):\n",
    "        \"\"\"尝试使用DeepSeek在线API\"\"\"\n",
    "        try:\n",
    "            import requests\n",
    "            \n",
    "            print(f\"尝试在线API: {self.config['deepseek_model']}\")\n",
    "            headers = {\n",
    "                'Authorization': f\"Bearer {self.config['deepseek_api_key']}\",\n",
    "                'Content-Type': 'application/json'\n",
    "            }\n",
    "            \n",
    "            data = {\n",
    "                'model': self.config['deepseek_model'],\n",
    "                'messages': [\n",
    "                    {'role': 'system', 'content': '你是一位专业的教育助手，请用适合中小学生理解的语言回答问题。'},\n",
    "                    {'role': 'user', 'content': original_question}\n",
    "                ],\n",
    "                'temperature': 0.7,\n",
    "                'max_tokens': 500\n",
    "            }\n",
    "            \n",
    "            response = requests.post(\n",
    "                'https://api.deepseek.com/v1/chat/completions',\n",
    "                headers=headers,\n",
    "                json=data,\n",
    "                timeout=self.config['timeout']\n",
    "            )\n",
    "            \n",
    "            if response.status_code == 200:\n",
    "                result = response.json()\n",
    "                answer = result['choices'][0]['message']['content'].strip()\n",
    "                if answer:\n",
    "                    print(\"✅ 在线API调用成功\")\n",
    "                    return f\"🌐 在线AI (DeepSeek) 回答：\\n\\n{answer}\"\n",
    "                else:\n",
    "                    print(\"⚠️ 在线API返回空回答\")\n",
    "            else:\n",
    "                print(f\"❌ 在线API调用失败，状态码: {response.status_code}, 响应: {response.text}\")\n",
    "                \n",
    "        except requests.exceptions.RequestException as e:\n",
    "            print(f\"在线API网络请求异常: {e}\")\n",
    "        except Exception as e:\n",
    "            print(f\"在线API调用未知异常: {e}\")\n",
    "        \n",
    "        return None\n",
    "\n",
    "\n",
    "\n",
    "    def _generate_enhanced_fallback(self, input_text):\n",
    "        \"\"\"生成增强的回退回答\"\"\"\n",
    "        if \"数学\" in input_text or \"计算\" in input_text or any(char.isdigit() for char in input_text):\n",
    "            return self._generate_enhanced_math_response(input_text)\n",
    "        elif \"语文\" in input_text or \"作文\" in input_text or \"阅读\" in input_text:\n",
    "            return self._generate_enhanced_chinese_response(input_text)\n",
    "        elif \"英语\" in input_text or \"English\" in input_text:\n",
    "            return self._generate_enhanced_english_response(input_text)\n",
    "        elif \"科学\" in input_text or \"实验\" in input_text or \"地球\" in input_text or \"四季\" in input_text or \"光合作用\" in input_text:\n",
    "            return self._generate_enhanced_science_response(input_text)\n",
    "        else:\n",
    "            return self._generate_general_response(input_text)\n",
    "\n",
    "    def _generate_enhanced_chinese_response(self, question):\n",
    "        \"\"\"增强的语文回答\"\"\"\n",
    "        if \"作文\" in question:\n",
    "            return \"\"\"📝 作文写作技巧：\n",
    "\n",
    "**写作步骤：**\n",
    "• **审题立意**：仔细读题，明确要求\n",
    "• **构思选材**：选择合适的素材\n",
    "• **列写提纲**：安排文章结构\n",
    "• **起草修改**：写初稿并完善\n",
    "\n",
    "📖 **作文结构：**\n",
    "• **开头**：开门见山，引人入胜\n",
    "• **中间**：条理清晰，详略得当\n",
    "• **结尾**：总结全文，点明主题\n",
    "\n",
    "✍️ **写作技巧：**\n",
    "• 多用比喻、拟人等修辞手法\n",
    "• 注意段落之间的过渡\n",
    "• 语言要生动具体\n",
    "• 表达真情实感\n",
    "\n",
    "💡 **提高方法：**\n",
    "多读书，多观察，多思考，多练笔！\"\"\"\n",
    "        elif \"阅读\" in question:\n",
    "            return \"\"\"📚 阅读理解方法：\n",
    "\n",
    "**阅读步骤：**\n",
    "• **初读**：了解文章大意\n",
    "• **细读**：理解重点内容\n",
    "• **精读**：分析写作手法\n",
    "• **总结**：归纳中心思想\n",
    "\n",
    "🔍 **理解技巧：**\n",
    "• 抓住关键词句\n",
    "• 理解段落大意\n",
    "• 分析人物性格\n",
    "• 体会作者情感\n",
    "\n",
    "📖 **答题方法：**\n",
    "• 仔细审题，明确要求\n",
    "• 回到原文找依据\n",
    "• 组织语言，条理清晰\n",
    "• 检查答案，确保完整\n",
    "\n",
    "记住：书读百遍，其义自见！\"\"\"\n",
    "\n",
    "        else:\n",
    "            return f\"\"\"📖 语文学习：{question}\n",
    "\n",
    "**语文学习要点：**\n",
    "• **多读**：培养语感，积累词汇\n",
    "• **多写**：练习表达，提高写作\n",
    "• **多思**：深入理解，培养思维\n",
    "• **多背**：积累名篇，丰富底蕴\n",
    "\n",
    "🎯 **学习方法：**\n",
    "• 课前预习，课后复习\n",
    "• 做好笔记，整理知识点\n",
    "• 多读经典，提高素养\n",
    "• 练习写作，表达思想\n",
    "\n",
    "语文是一切学科的基础，要用心学习哦！\"\"\"\n",
    "\n",
    "    def _generate_enhanced_english_response(self, question):\n",
    "        \"\"\"增强的英语回答\"\"\"\n",
    "        if \"现在进行时\" in question:\n",
    "            return \"\"\"⏰ 现在进行时详解：\n",
    "\n",
    "**结构：** be动词 + 动词ing\n",
    "\n",
    "**用法：**\n",
    "• 表示正在进行的动作\n",
    "• 表示现阶段正在进行的动作\n",
    "\n",
    "📝 **例句：**\n",
    "• I am reading a book. (我正在读书)\n",
    "• She is playing piano. (她正在弹钢琴)\n",
    "• They are studying English. (他们正在学英语)\n",
    "\n",
    "🔄 **动词变化规则：**\n",
    "• 一般情况：直接加ing (read→reading)\n",
    "• 以e结尾：去e加ing (write→writing)\n",
    "• 重读闭音节：双写末尾字母加ing (run→running)\n",
    "\n",
    "💡 **记忆口诀：**\n",
    "be动词加动词ing，正在进行要记清！\"\"\"\n",
    "\n",
    "        else:\n",
    "            return f\"\"\"🌍 English Learning: {question}\n",
    "\n",
    "**学习英语的方法：**\n",
    "• **Listen**: 多听英语材料，培养语感\n",
    "• **Speak**: 大胆开口说，不怕犯错\n",
    "• **Read**: 阅读英语文章，扩大词汇\n",
    "• **Write**: 练习写作，巩固语法\n",
    "\n",
    "🎯 **学习技巧：**\n",
    "• 每天坚持学习30分钟\n",
    "• 看英语动画片和电影\n",
    "• 听英语歌曲\n",
    "• 和同学用英语对话\n",
    "\n",
    "Remember: Practice makes perfect! 多练习就能提高！\"\"\"\n",
    "\n",
    "    def _generate_general_response(self, question):\n",
    "        \"\"\"通用增强回答\"\"\"\n",
    "        return f\"\"\"💡 关于您的问题：{question}\n",
    "\n",
    "🎓 **作为您的教育助手，我来为您详细解答：**\n",
    "\n",
    "这是一个很好的问题！学习就是要多思考、多提问。\n",
    "\n",
    "📚 **学习建议：**\n",
    "• **保持好奇心**：勇于提问，探索未知\n",
    "• **多角度思考**：从不同方面分析问题\n",
    "• **理论联系实际**：将知识运用到生活中\n",
    "• **及时复习巩固**：温故而知新\n",
    "\n",
    "🌟 **成长心得：**\n",
    "• 每个问题都是学习的机会\n",
    "• 不懂就问是好习惯\n",
    "• 坚持学习，持续进步\n",
    "• 相信自己，勇敢尝试\n",
    "如果您需要更具体的解答，请提供更多细节，我会给出更详细的回答！\"\"\"\n",
    "    def _generate_enhanced_math_response(self, question):\n",
    "        \"\"\"增强的数学回答\"\"\"\n",
    "        if \"面积\" in question:\n",
    "            return \"\"\"📐 面积计算方法：\n",
    "\n",
    "**常见图形面积公式：**\n",
    "• **正方形**：面积 = 边长 × 边长 = a²\n",
    "• **长方形**：面积 = 长 × 宽 = l × w  \n",
    "• **三角形**：面积 = 底 × 高 ÷ 2 = (b × h) ÷ 2\n",
    "• **圆形**：面积 = π × 半径² = π × r²\n",
    "• **平行四边形**：面积 = 底 × 高 = b × h\n",
    "\n",
    "🔍 **解题步骤：**\n",
    "1. 确定图形类型\n",
    "2. 找出已知条件\n",
    "3. 选择合适公式\n",
    "4. 代入数值计算\n",
    "5. 检查答案合理性\n",
    "\n",
    "💡 **记忆技巧：**\n",
    "正方形像豆腐块，边长相乘就是它！\n",
    "长方形像课桌面，长乘宽来算面积！\"\"\"\n",
    "\n",
    "        elif \"分数\" in question:\n",
    "            return \"\"\"🔢 分数运算详解：\n",
    "\n",
    "**分数加法：**\n",
    "• 同分母：分子相加，分母不变\n",
    "  例：1/5 + 2/5 = 3/5\n",
    "• 异分母：先通分，再相加\n",
    "  例：1/2 + 1/3 = 3/6 + 2/6 = 5/6\n",
    "\n",
    "**分数减法：**\n",
    "• 同分母：分子相减，分母不变\n",
    "• 异分母：先通分，再相减\n",
    "\n",
    "**分数乘法：**\n",
    "• 分子乘分子，分母乘分母\n",
    "  例：2/3 × 3/4 = 6/12 = 1/2\n",
    "\n",
    "**分数除法：**\n",
    "• 除以一个分数 = 乘以它的倒数\n",
    "  例：2/3 ÷ 1/2 = 2/3 × 2/1 = 4/3\n",
    "\n",
    "🎯 **关键技巧：**\n",
    "通分找最小公倍数，约分找最大公约数！\"\"\"\n",
    "\n",
    "        else:\n",
    "            return f\"\"\"📊 数学问题：{question}\n",
    "\n",
    "🧮 **数学学习方法：**\n",
    "• **理解概念**：先理解原理，再记公式\n",
    "• **多做练习**：熟能生巧，提高计算速度\n",
    "• **检查验算**：养成检查的好习惯\n",
    "• **总结规律**：找出题目的共同特点\n",
    "\n",
    "💪 **解题技巧：**\n",
    "1. 仔细审题，理解题意\n",
    "2. 画图辅助，直观理解\n",
    "3. 分步计算，避免错误\n",
    "4. 验证答案，确保正确\n",
    "\n",
    "记住：数学是思维的体操，多练习就能提高！\"\"\"\n",
    "\n",
    "    def _generate_enhanced_science_response(self, question):\n",
    "        \"\"\"增强的科学回答\"\"\"\n",
    "        if \"四季\" in question:\n",
    "            return \"\"\"🌍 地球四季形成的原因：\n",
    "\n",
    "**核心原理：地球公转 + 地轴倾斜**\n",
    "\n",
    "🔄 **详细过程：**\n",
    "• **地球公转**：地球围绕太阳运行，一年365天\n",
    "• **地轴倾斜**：地球自转轴倾斜23.5°（这是关键！）\n",
    "• **阳光直射点变化**：导致不同地区接受阳光的角度和时间不同\n",
    "\n",
    "📅 **四季变化：**\n",
    "• **春季**（3-5月）：阳光直射赤道，昼夜等长，万物复苏\n",
    "• **夏季**（6-8月）：阳光直射北回归线，北半球白天长，炎热\n",
    "• **秋季**（9-11月）：阳光再次直射赤道，昼夜等长，收获\n",
    "• **冬季**（12-2月）：阳光直射南回归线，北半球白天短，寒冷\n",
    "\n",
    "🔬 **科学实验：**\n",
    "用手电筒照地球仪，慢慢转动，观察光照变化！\n",
    "\n",
    "💡 **记忆口诀：**\n",
    "地轴倾斜是关键，公转一圈四季现！\"\"\"\n",
    "\n",
    "        elif \"光合作用\" in question:\n",
    "            return \"\"\"🌱 光合作用详解：\n",
    "\n",
    "**定义：** 植物利用阳光制造养分的神奇过程\n",
    "\n",
    "⚗️ **化学方程式：**\n",
    "6CO₂ + 6H₂O + 光能 → C₆H₁₂O₆ + 6O₂\n",
    "二氧化碳 + 水 + 光能 → 葡萄糖 + 氧气\n",
    "\n",
    "🔍 **详细过程：**\n",
    "• **原料**：二氧化碳（空气中）+ 水（根部吸收）\n",
    "• **条件**：阳光照射 + 叶绿素催化\n",
    "• **场所**：主要在叶片的叶绿体中\n",
    "• **产物**：葡萄糖（植物食物）+ 氧气（释放到空气）\n",
    "\n",
    "🌿 **重要意义：**\n",
    "1. **制造食物**：为植物提供营养\n",
    "2. **产生氧气**：我们呼吸的氧气来源\n",
    "3. **净化空气**：吸收二氧化碳\n",
    "4. **维持生态**：地球生命的基础\n",
    "\n",
    "🧪 **趣味实验：**\n",
    "把植物放在黑暗中几天，叶子变黄，证明光合作用需要光！\n",
    "\n",
    "🎯 **记忆要点：**\n",
    "阳光水和二氧化碳，叶绿体里变食粮！\"\"\"\n",
    "\n",
    "        else:\n",
    "            return f\"\"\"🔬 科学探索：{question}\n",
    "\n",
    "**科学学习方法：**\n",
    "• **观察**：仔细观察现象，记录细节\n",
    "• **假设**：提出可能的解释\n",
    "• **实验**：设计实验来验证假设\n",
    "• **结论**：总结规律和原理\n",
    "\n",
    "🌟 **科学精神：**\n",
    "• 保持好奇心，多问\"为什么\"\n",
    "• 勇于探索，不怕失败\n",
    "• 实事求是，相信证据\n",
    "• 持续学习，更新认知\n",
    "\n",
    "🔍 **学习建议：**\n",
    "• 多动手做实验\n",
    "• 观察生活中的科学现象\n",
    "• 阅读科普书籍\n",
    "• 培养逻辑思维\n",
    "\n",
    "科学就在我们身边，从日常生活中发现科学的奥秘吧！\"\"\"\n",
    "\n",
    "# ================== 数据管理模块 ==================\n",
    "class DataManager:\n",
    "    def __init__(self):\n",
    "        self.timetable = self._load_timetable()\n",
    "        self.homework_records = []\n",
    "\n",
    "    def _load_timetable(self):\n",
    "        return {\n",
    "            \"Monday\": [\"语文\", \"数学\", \"英语\", \"体育\"],\n",
    "            \"Tuesday\": [\"数学\", \"科学\", \"音乐\", \"美术\"],\n",
    "            \"Wednesday\": [\"语文\", \"英语\", \"体育\", \"手工\"],\n",
    "            \"Thursday\": [\"数学\", \"科学\", \"语文\", \"音乐\"],\n",
    "            \"Friday\": [\"英语\", \"体育\", \"美术\", \"班会\"],\n",
    "            \"Saturday\": [\"兴趣课\", \"阅读时间\"],\n",
    "            \"Sunday\": [\"休息日\", \"家庭作业时间\"]\n",
    "        }\n",
    "\n",
    "    def store_data(self, data_type, content):\n",
    "        if data_type == \"homework\":\n",
    "            self.homework_records.append({\n",
    "                \"content\": content,\n",
    "                \"timestamp\": datetime.now().isoformat(),\n",
    "                \"status\": \"submitted\"\n",
    "            })\n",
    "        elif data_type == \"timetable\":\n",
    "            self.timetable.update(content)\n",
    "\n",
    "    def retrieve_data(self, data_type, condition):\n",
    "        if data_type == \"timetable\":\n",
    "            return {\n",
    "                \"courses\": self.timetable.get(condition, [\"今日无课程安排\"])\n",
    "            }\n",
    "        elif data_type == \"homework\":\n",
    "            return [h for h in self.homework_records if condition in str(h)]\n",
    "\n",
    "# ================== 核心功能模块 ==================\n",
    "class EduCore:\n",
    "    def __init__(self):\n",
    "        self.model_mgr = ModelManager()\n",
    "        self.data_mgr = DataManager()\n",
    "        self.model_mgr.load_model()\n",
    "\n",
    "    def ask_question(self, question):\n",
    "        if not question.strip():\n",
    "            return \"请输入您的问题，我会尽力帮助您！\"\n",
    "        \n",
    "        # 直接传递问题，不添加额外前缀\n",
    "        response = self.model_mgr.run_inference(question)\n",
    "        return response\n",
    "\n",
    "    def grade_homework(self, problem, answer):\n",
    "        if not problem.strip() or not answer.strip():\n",
    "            return {\"score\": 0, \"feedback\": \"请提供完整的题目和答案\"}\n",
    "        \n",
    "        # 创建AI批改提示词\n",
    "        prompt = self._create_grading_prompt(problem, answer)\n",
    "        \n",
    "        # 调用AI进行批改\n",
    "        ai_feedback = self.model_mgr.run_inference(prompt)\n",
    "        \n",
    "        # 从AI反馈中提取分数和评语 (需要根据AI的实际输出来调整)\n",
    "        score, feedback = self._parse_ai_grading_response(ai_feedback, problem, answer)\n",
    "        \n",
    "        # 存储作业记录\n",
    "        self.data_mgr.store_data(\"homework\", {\n",
    "            \"problem\": problem,\n",
    "            \"answer\": answer,\n",
    "            \"score\": score,\n",
    "            \"feedback\": feedback,\n",
    "            \"ai_raw_feedback\": ai_feedback # 存储原始AI反馈用于调试\n",
    "        })\n",
    "        \n",
    "        return {\"score\": score, \"feedback\": feedback}\n",
    "\n",
    "    def _create_grading_prompt(self, problem, student_answer):\n",
    "        \"\"\"创建用于AI作业批改的提示词\"\"\"\n",
    "        return f\"\"\"你是一位严格且逻辑清晰的老师，请批改以下学生的作业。\n",
    "\n",
    "    作业题目：\n",
    "    {problem}\n",
    "\n",
    "    学生答案：\n",
    "    {student_answer}\n",
    "\n",
    "    批改要求：\n",
    "    1.  **核心任务**：首先，请独立计算出题目的正确答案。\n",
    "    2.  **答案对比**：将学生答案与你计算出的正确答案进行严格对比。\n",
    "    3.  **正确性判断**：明确指出学生答案是“完全正确”、“部分正确”、“完全错误”或“无法判断”。\n",
    "    4.  **评分**：\n",
    "        *   如果学生答案“完全正确”，请给出90-100分。\n",
    "        *   如果学生答案“部分正确”（例如，步骤正确但计算错误，或部分概念理解正确），请根据正确程度给出60-89分。\n",
    "        *   如果学生答案“完全错误”，请给出0-59分。\n",
    "    5.  **评语**：\n",
    "        *   评语必须与正确性判断和分数保持严格一致。\n",
    "        *   如果答案错误，请明确指出错误点，并给出正确的解题思路或答案。\n",
    "        *   如果答案正确，可以适当表扬，并鼓励学生继续努力。\n",
    "        *   评语应具有建设性，帮助学生理解。\n",
    "        *   如果得分不是满分，请给出扣分理由和改进建议。\n",
    "    6.  **输出格式**：请严格按照以下格式输出，不要添加任何额外说明或无关内容：\n",
    "        正确答案：[此处填写你计算的正确答案]\n",
    "        学生答案评估：[此处填写“完全正确”、“部分正确”或“完全错误”]\n",
    "        分数：[此处填写0-100的整数分数]\n",
    "        评语：[此处填写详细评语]\n",
    "\n",
    "    请开始批改：\"\"\"\n",
    "\n",
    "    def _parse_ai_grading_response(self, ai_response, problem, student_answer):\n",
    "        \"\"\"解析AI批改结果，提取分数和评语\"\"\"\n",
    "        try:\n",
    "            score_line = \"\"\n",
    "            feedback_lines = []\n",
    "            \n",
    "            # 尝试从AI响应中提取分数和评语\n",
    "            for line in ai_response.split('\\n'):\n",
    "                if \"分数：\" in line:\n",
    "                    score_line = line.replace(\"分数：\", \"\").strip()\n",
    "                elif \"评语：\" in line:\n",
    "                    feedback_lines.append(line.replace(\"评语：\", \"\").strip())\n",
    "                elif feedback_lines: # 如果已经开始收集评语，则后续行都视为评语\n",
    "                    feedback_lines.append(line.strip())\n",
    "            \n",
    "            score = 0\n",
    "            if score_line:\n",
    "                try:\n",
    "                    score = int(score_line)\n",
    "                    if not (0 <= score <= 100):\n",
    "                        score = 75 # 默认分数\n",
    "                except ValueError:\n",
    "                    score = 70 # 解析失败给默认分\n",
    "            else: # 如果AI没有明确给出分数，尝试根据关键词判断\n",
    "                if \"正确\" in ai_response or \"非常好\" in ai_response:\n",
    "                    score = 90\n",
    "                elif \"部分正确\" in ai_response or \"基本正确\" in ai_response:\n",
    "                    score = 75\n",
    "                elif \"错误\" in ai_response or \"不正确\" in ai_response:\n",
    "                    score = 50\n",
    "                else:\n",
    "                    score = 65 # 无法判断给一个基础分\n",
    "\n",
    "            feedback = \"\\n\".join(feedback_lines).strip()\n",
    "            if not feedback:\n",
    "                feedback = ai_response # 如果无法解析，直接返回原始AI响应作为评语\n",
    "                \n",
    "            # 确保分数在0-100之间\n",
    "            score = max(0, min(100, score))\n",
    "                \n",
    "            return score, feedback\n",
    "        except Exception as e:\n",
    "            print(f\"解析AI批改结果失败: {e}\")\n",
    "            # 如果解析失败，返回一个默认的、基于简单规则的批改\n",
    "            return self._calculate_score(problem, student_answer, \"AI反馈解析失败，请检查AI输出格式。\"), \"AI反馈解析失败，请检查AI输出格式。\"\n",
    "\n",
    "    def query_timetable(self):\n",
    "        try:\n",
    "            weekday = datetime.now().strftime(\"%A\")  # 获取当前星期几，例如 \"Monday\"\n",
    "            courses = self.data_mgr.retrieve_data(\"timetable\", weekday)\n",
    "            return {\n",
    "                \"date\": datetime.now().isoformat(),\n",
    "                \"weekday\": weekday,\n",
    "                \"timetable\": courses.get(\"courses\", [\"今日无课程安排\"])\n",
    "            }\n",
    "        except Exception as e:\n",
    "            print(f\"查询课表失败: {e}\")\n",
    "            return {\n",
    "                \"date\": datetime.now().isoformat(),\n",
    "                \"weekday\": \"未知\",\n",
    "                \"timetable\": [\"课表加载失败，请稍后再试\"]\n",
    "            }\n",
    "\n",
    "# ================== 接口模块 ==================\n",
    "class EduInterface:\n",
    "    def __init__(self):\n",
    "        self.core = EduCore()\n",
    "        self.app = Flask(__name__)\n",
    "        self.setup_routes()\n",
    "\n",
    "    def setup_routes(self):\n",
    "        @self.app.route('/')\n",
    "        def index():\n",
    "            return '''\n",
    "            <!DOCTYPE html>\n",
    "            <html lang=\"zh-CN\">\n",
    "            <head>\n",
    "                <meta charset=\"UTF-8\">\n",
    "                <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n",
    "                <title>教育助手系统</title>\n",
    "                <style>\n",
    "                    * {\n",
    "                        margin: 0;\n",
    "                        padding: 0;\n",
    "                        box-sizing: border-box;\n",
    "                    }\n",
    "                    \n",
    "                    body {\n",
    "                        font-family: 'Microsoft YaHei', Arial, sans-serif;\n",
    "                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n",
    "                        min-height: 100vh;\n",
    "                        padding: 20px;\n",
    "                    }\n",
    "                    \n",
    "                    .container {\n",
    "                        max-width: 1200px;\n",
    "                        margin: 0 auto;\n",
    "                        background: white;\n",
    "                        border-radius: 15px;\n",
    "                        box-shadow: 0 10px 30px rgba(0,0,0,0.2);\n",
    "                        overflow: hidden;\n",
    "                    }\n",
    "                    \n",
    "                    .header {\n",
    "                        position: relative;\n",
    "                        background: linear-gradient(45deg, #4CAF50, #45a049);\n",
    "                        color: white;\n",
    "                        padding: 30px;\n",
    "                        text-align: center;\n",
    "                    }\n",
    "                    \n",
    "                    .header h1 {\n",
    "                        font-size: 2.5em;\n",
    "                        margin-bottom: 10px;\n",
    "                    }\n",
    "                    \n",
    "                    .header p {\n",
    "                        font-size: 1.2em;\n",
    "                        opacity: 0.9;\n",
    "                    }\n",
    "                    \n",
    "                    .tabs {\n",
    "                        display: flex;\n",
    "                        background: #f5f5f5;\n",
    "                        border-bottom: 1px solid #ddd;\n",
    "                    }\n",
    "                    \n",
    "                    .tab-button {\n",
    "                        flex: 1;\n",
    "                        padding: 15px 20px;\n",
    "                        background: none;\n",
    "                        border: none;\n",
    "                        cursor: pointer;\n",
    "                        font-size: 16px;\n",
    "                        transition: all 0.3s;\n",
    "                        border-bottom: 3px solid transparent;\n",
    "                    }\n",
    "                    \n",
    "                    .tab-button:hover {\n",
    "                        background: #e9e9e9;\n",
    "                    }\n",
    "                    \n",
    "                    .tab-button.active {\n",
    "                        background: white;\n",
    "                        border-bottom-color: #4CAF50;\n",
    "                        color: #4CAF50;\n",
    "                        font-weight: bold;\n",
    "                    }\n",
    "                    \n",
    "                    .tab-content {\n",
    "                        display: none;\n",
    "                        padding: 30px;\n",
    "                    }\n",
    "                    \n",
    "                    .tab-content.active {\n",
    "                        display: block;\n",
    "                    }\n",
    "                    \n",
    "                    .form-group {\n",
    "                        margin-bottom: 20px;\n",
    "                    }\n",
    "                    \n",
    "                    label {\n",
    "                        display: block;\n",
    "                        margin-bottom: 8px;\n",
    "                        font-weight: bold;\n",
    "                        color: #333;\n",
    "                    }\n",
    "                    \n",
    "                    input, textarea {\n",
    "                        width: 100%;\n",
    "                        padding: 12px;\n",
    "                        border: 2px solid #ddd;\n",
    "                        border-radius: 8px;\n",
    "                        font-size: 16px;\n",
    "                        transition: border-color 0.3s;\n",
    "                    }\n",
    "                    \n",
    "                    input:focus, textarea:focus {\n",
    "                        outline: none;\n",
    "                        border-color: #4CAF50;\n",
    "                    }\n",
    "                    \n",
    "                    textarea {\n",
    "                        min-height: 120px;\n",
    "                        resize: vertical;\n",
    "                    }\n",
    "                    \n",
    "                    .btn {\n",
    "                        background: linear-gradient(45deg, #4CAF50, #45a049);\n",
    "                        color: white;\n",
    "                        padding: 12px 30px;\n",
    "                        border: none;\n",
    "                        border-radius: 8px;\n",
    "                        font-size: 16px;\n",
    "                        cursor: pointer;\n",
    "                        transition: all 0.3s;\n",
    "                    }\n",
    "                    \n",
    "                    .btn:hover {\n",
    "                        transform: translateY(-2px);\n",
    "                        box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);\n",
    "                    }\n",
    "                    \n",
    "                    .result {\n",
    "                        margin-top: 20px;\n",
    "                        padding: 20px;\n",
    "                        background: #f8f9fa;\n",
    "                        border-radius: 8px;\n",
    "                        border-left: 4px solid #4CAF50;\n",
    "                        display: none;\n",
    "                    }\n",
    "                    \n",
    "                    .result.show {\n",
    "                        display: block;\n",
    "                        animation: fadeIn 0.5s;\n",
    "                    }\n",
    "                    \n",
    "                    @keyframes fadeIn {\n",
    "                        from { opacity: 0; transform: translateY(10px); }\n",
    "                        to { opacity: 1; transform: translateY(0); }\n",
    "                    }\n",
    "                    \n",
    "                    .loading {\n",
    "                        display: none;\n",
    "                        text-align: center;\n",
    "                        padding: 20px;\n",
    "                    }\n",
    "                    \n",
    "                    .spinner {\n",
    "                        border: 4px solid #f3f3f3;\n",
    "                        border-top: 4px solid #4CAF50;\n",
    "                        border-radius: 50%;\n",
    "                        width: 40px;\n",
    "                        height: 40px;\n",
    "                        animation: spin 1s linear infinite;\n",
    "                        margin: 0 auto 10px;\n",
    "                    }\n",
    "                    \n",
    "                    @keyframes spin {\n",
    "                        0% { transform: rotate(0deg); }\n",
    "                        100% { transform: rotate(360deg); }\n",
    "                    }\n",
    "                    \n",
    "                    .score {\n",
    "                        font-size: 24px;\n",
    "                        font-weight: bold;\n",
    "                        color: #4CAF50;\n",
    "                        margin-bottom: 10px;\n",
    "                    }\n",
    "                    \n",
    "                    .timetable-grid {\n",
    "                        display: grid;\n",
    "                        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));\n",
    "                        gap: 15px;\n",
    "                        margin-top: 20px;\n",
    "                    }\n",
    "                    \n",
    "                    .course-card {\n",
    "                        background: linear-gradient(45deg, #667eea, #764ba2);\n",
    "                        color: white;\n",
    "                        padding: 20px;\n",
    "                        border-radius: 10px;\n",
    "                        text-align: center;\n",
    "                        font-weight: bold;\n",
    "                        font-size: 18px;\n",
    "                    }\n",
    "\n",
    "                    .header-controls {\n",
    "                        position: absolute;\n",
    "                        top: 20px;\n",
    "                        right: 20px;\n",
    "                        text-align: right;\n",
    "                    }\n",
    "\n",
    "                    .exit-btn {\n",
    "                        background: rgba(255,255,255,0.2);\n",
    "                        color: white;\n",
    "                        border: 2px solid white;\n",
    "                        padding: 10px 20px;\n",
    "                        border-radius: 25px;\n",
    "                        cursor: pointer;\n",
    "                        font-size: 14px;\n",
    "                        transition: all 0.3s;\n",
    "                        margin-bottom: 5px;\n",
    "                        display: block;\n",
    "                    }\n",
    "\n",
    "                    .exit-btn:hover {\n",
    "                        background: rgba(255,255,255,0.3);\n",
    "                        transform: scale(1.05);\n",
    "                    }\n",
    "\n",
    "                    .exit-hint {\n",
    "                        font-size: 12px;\n",
    "                        opacity: 0.8;\n",
    "                        color: white;\n",
    "                    }\n",
    "\n",
    "                    @keyframes spin {\n",
    "                        0% { transform: rotate(0deg); }\n",
    "                        100% { transform: rotate(360deg); }\n",
    "                    }\n",
    "                </style>\n",
    "            </head>\n",
    "            <body>\n",
    "                <div class=\"container\">\n",
    "                    <div class=\"header\">\n",
    "                        <h1>🎓 教育助手系统</h1>\n",
    "                        <p>您的智能学习伙伴，随时为您答疑解惑</p>\n",
    "                        <div class=\"header-controls\">\n",
    "                            <button class=\"exit-btn\" onclick=\"exitSystem()\">🚪 退出系统</button>\n",
    "                            <div class=\"exit-hint\">快捷键: Ctrl+Q</div>\n",
    "                        </div>\n",
    "                    </div>\n",
    "\n",
    "                    <div class=\"tabs\">\n",
    "                        <button class=\"tab-button active\" onclick=\"showTab('ask')\">💬 智能问答</button>\n",
    "                        <button class=\"tab-button\" onclick=\"showTab('grade')\">📝 作业批改</button>\n",
    "                        <button class=\"tab-button\" onclick=\"showTab('timetable')\">📅 课程查询</button>\n",
    "                    </div>\n",
    "\n",
    "                    <!-- 智能问答标签页 -->\n",
    "                    <div id=\"ask\" class=\"tab-content active\">\n",
    "                        <h2>💬 智能问答</h2>\n",
    "                        <p>有任何学习问题都可以问我哦！</p>\n",
    "\n",
    "                        <div class=\"form-group\">\n",
    "                            <label for=\"question\">请输入您的问题：</label>\n",
    "                            <textarea id=\"question\" placeholder=\"例如：什么是光合作用？数学中的分数如何计算？\"></textarea>\n",
    "                        </div>\n",
    "\n",
    "                        <button class=\"btn\" onclick=\"askQuestion()\">🚀 提问</button>\n",
    "\n",
    "                        <div class=\"loading\" id=\"askLoading\">\n",
    "                            <div class=\"spinner\"></div>\n",
    "                            <p>AI正在思考中...</p>\n",
    "                        </div>\n",
    "\n",
    "                        <div class=\"result\" id=\"askResult\">\n",
    "                            <h3>📖 AI回答：</h3>\n",
    "                            <div id=\"answerContent\"></div>\n",
    "                        </div>\n",
    "                    </div>\n",
    "\n",
    "                    <!-- 作业批改标签页 -->\n",
    "                    <div id=\"grade\" class=\"tab-content\">\n",
    "                        <h2>📝 作业批改</h2>\n",
    "                        <p>提交您的作业，我来帮您批改和评分！</p>\n",
    "\n",
    "                        <div class=\"form-group\">\n",
    "                            <label for=\"problem\">题目内容：</label>\n",
    "                            <textarea id=\"problem\" placeholder=\"例如：计算 25 + 37 = ?\"></textarea>\n",
    "                        </div>\n",
    "\n",
    "                        <div class=\"form-group\">\n",
    "                            <label for=\"answer\">您的答案：</label>\n",
    "                            <textarea id=\"answer\" placeholder=\"请输入您的答案\"></textarea>\n",
    "                        </div>\n",
    "\n",
    "                        <button class=\"btn\" onclick=\"gradeHomework()\">✅ 提交批改</button>\n",
    "\n",
    "                        <div class=\"loading\" id=\"gradeLoading\">\n",
    "                            <div class=\"spinner\"></div>\n",
    "                            <p>正在批改中...</p>\n",
    "                        </div>\n",
    "\n",
    "                        <div class=\"result\" id=\"gradeResult\">\n",
    "                            <h3>📊 批改结果：</h3>\n",
    "                            <div class=\"score\" id=\"scoreDisplay\"></div>\n",
    "                            <div id=\"feedbackContent\"></div>\n",
    "                        </div>\n",
    "                    </div>\n",
    "\n",
    "                    <!-- 课程查询标签页 -->\n",
    "                    <div id=\"timetable\" class=\"tab-content\">\n",
    "                        <h2>📅 课程查询</h2>\n",
    "                        <p>查看今日的课程安排</p>\n",
    "\n",
    "                        <button class=\"btn\" onclick=\"getTimetable()\">🔄 刷新课表</button>\n",
    "\n",
    "                        <div class=\"loading\" id=\"timetableLoading\">\n",
    "                            <div class=\"spinner\"></div>\n",
    "                            <p>正在加载课表...</p>\n",
    "                        </div>\n",
    "\n",
    "                        <div class=\"result\" id=\"timetableResult\">\n",
    "                            <h3>📚 今日课程：</h3>\n",
    "                            <div class=\"timetable-grid\" id=\"timetableGrid\"></div>\n",
    "                        </div>\n",
    "                    </div>\n",
    "                </div>\n",
    "\n",
    "                <script>\n",
    "                    // 标签页切换\n",
    "                    function showTab(tabName) {\n",
    "                        // 隐藏所有标签页内容\n",
    "                        document.querySelectorAll('.tab-content').forEach(tab => {\n",
    "                            tab.classList.remove('active');\n",
    "                        });\n",
    "                        \n",
    "                        // 移除所有按钮的active类\n",
    "                        document.querySelectorAll('.tab-button').forEach(btn => {\n",
    "                            btn.classList.remove('active');\n",
    "                        });\n",
    "                        \n",
    "                        // 显示选中的标签页\n",
    "                        document.getElementById(tabName).classList.add('active');\n",
    "                        event.target.classList.add('active');\n",
    "                    }\n",
    "                    \n",
    "                    // 智能问答功能\n",
    "                    async function askQuestion() {\n",
    "                        const question = document.getElementById('question').value.trim();\n",
    "                        if (!question) {\n",
    "                            alert('请输入问题！');\n",
    "                            return;\n",
    "                        }\n",
    "                        \n",
    "                        const loading = document.getElementById('askLoading');\n",
    "                        const result = document.getElementById('askResult');\n",
    "                        const answerContent = document.getElementById('answerContent');\n",
    "                        \n",
    "                        loading.style.display = 'block';\n",
    "                        result.classList.remove('show');\n",
    "                        \n",
    "                        try {\n",
    "                            const response = await fetch('/ask', {\n",
    "                                method: 'POST',\n",
    "                                headers: {\n",
    "                                    'Content-Type': 'application/json',\n",
    "                                },\n",
    "                                body: JSON.stringify({ question: question })\n",
    "                            });\n",
    "                            \n",
    "                            const data = await response.json();\n",
    "                            answerContent.innerHTML = data.answer;\n",
    "                            \n",
    "                            loading.style.display = 'none';\n",
    "                            result.classList.add('show');\n",
    "                        } catch (error) {\n",
    "                            loading.style.display = 'none';\n",
    "                            alert('请求失败，请稍后重试！');\n",
    "                        }\n",
    "                    }\n",
    "                    \n",
    "                    // 作业批改功能\n",
    "                    async function gradeHomework() {\n",
    "                        const problem = document.getElementById('problem').value.trim();\n",
    "                        const answer = document.getElementById('answer').value.trim();\n",
    "                        \n",
    "                        if (!problem || !answer) {\n",
    "                            alert('请填写完整的题目和答案！');\n",
    "                            return;\n",
    "                        }\n",
    "                        \n",
    "                        const loading = document.getElementById('gradeLoading');\n",
    "                        const result = document.getElementById('gradeResult');\n",
    "                        const scoreDisplay = document.getElementById('scoreDisplay');\n",
    "                        const feedbackContent = document.getElementById('feedbackContent');\n",
    "                        \n",
    "                        loading.style.display = 'block';\n",
    "                        result.classList.remove('show');\n",
    "                        \n",
    "                        try {\n",
    "                            const response = await fetch('/grade', {\n",
    "                                method: 'POST',\n",
    "                                headers: {\n",
    "                                    'Content-Type': 'application/json',\n",
    "                                },\n",
    "                                body: JSON.stringify({ problem: problem, answer: answer })\n",
    "                            });\n",
    "                            \n",
    "                            const data = await response.json();\n",
    "                            scoreDisplay.innerHTML = `得分：${data.score} 分`;\n",
    "                            feedbackContent.innerHTML = data.feedback;\n",
    "                            \n",
    "                            loading.style.display = 'none';\n",
    "                            result.classList.add('show');\n",
    "                        } catch (error) {\n",
    "                            loading.style.display = 'none';\n",
    "                            alert('请求失败，请稍后重试！');\n",
    "                        }\n",
    "                    }\n",
    "                    \n",
    "                    // 课程查询功能\n",
    "                    async function getTimetable() {\n",
    "                        const loading = document.getElementById('timetableLoading');\n",
    "                        const result = document.getElementById('timetableResult');\n",
    "                        const timetableGrid = document.getElementById('timetableGrid');\n",
    "                        \n",
    "                        loading.style.display = 'block';\n",
    "                        result.classList.remove('show');\n",
    "                        \n",
    "                        try {\n",
    "                            const response = await fetch('/timetable');\n",
    "                            const data = await response.json();\n",
    "                            \n",
    "                            if (!data.success) {\n",
    "                                throw new Error(data.message);\n",
    "                            }\n",
    "                            \n",
    "                            timetableGrid.innerHTML = '';\n",
    "                            data.data.timetable.forEach(course => {\n",
    "                                const courseCard = document.createElement('div');\n",
    "                                courseCard.className = 'course-card';\n",
    "                                courseCard.textContent = course;\n",
    "                                timetableGrid.appendChild(courseCard);\n",
    "                            });\n",
    "                            \n",
    "                            loading.style.display = 'none';\n",
    "                            result.classList.add('show');\n",
    "                        } catch (error) {\n",
    "                            loading.style.display = 'none';\n",
    "                            alert(`获取课表失败：${error.message}`);\n",
    "                        }\n",
    "                    }\n",
    "                    \n",
    "                    // 页面加载时自动加载课表\n",
    "                    window.onload = function() {\n",
    "                        getTimetable(); // 页面加载时自动加载课表\n",
    "                    };\n",
    "                    \n",
    "                    // 回车键提交\n",
    "                    document.getElementById('question').addEventListener('keypress', function(e) {\n",
    "                        if (e.key === 'Enter' && e.ctrlKey) {\n",
    "                            askQuestion();\n",
    "                        }\n",
    "                    });\n",
    "                    \n",
    "                    document.getElementById('answer').addEventListener('keypress', function(e) {\n",
    "                        if (e.key === 'Enter' && e.ctrlKey) {\n",
    "                            gradeHomework();\n",
    "                        }\n",
    "                    });\n",
    "                    \n",
    "                    // 添加一些示例问题\n",
    "                    function addExampleQuestions() {\n",
    "                        const examples = [\n",
    "                            \"什么是光合作用？\",\n",
    "                            \"如何计算圆的面积？\",\n",
    "                            \"英语中现在进行时怎么用？\",\n",
    "                            \"地球为什么会有四季？\",\n",
    "                            \"分数的加法怎么算？\"\n",
    "                        ];\n",
    "                        \n",
    "                        const questionInput = document.getElementById('question');\n",
    "                        const randomExample = examples[Math.floor(Math.random() * examples.length)];\n",
    "                        questionInput.placeholder = `例如：${randomExample}`;\n",
    "                    }\n",
    "                    \n",
    "                    // 页面加载完成后执行\n",
    "                    document.addEventListener('DOMContentLoaded', function() {\n",
    "                        addExampleQuestions();\n",
    "                        // 每30秒更换一次示例问题\n",
    "                        setInterval(addExampleQuestions, 30000);\n",
    "                    });\n",
    "                    \n",
    "                    // 退出系统功能\n",
    "                    async function exitSystem() {\n",
    "                        if (confirm('确定要退出教育助手系统吗？\\\\n这将关闭整个服务器。')) {\n",
    "                            try {\n",
    "                                // 显示退出中的状态\n",
    "                                document.body.innerHTML = `\n",
    "                                    <div style=\"display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-align: center; font-family: 'Microsoft YaHei';\">\n",
    "                                        <div>\n",
    "                                            <div style=\"border: 4px solid rgba(255,255,255,0.3); border-top: 4px solid white; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin: 0 auto 20px;\"></div>\n",
    "                                            <h1>正在退出系统...</h1>\n",
    "                                            <p style=\"font-size: 18px; margin: 20px 0;\">感谢使用教育助手系统！</p>\n",
    "                                        </div>\n",
    "                                    </div>\n",
    "                                `;\n",
    "                                \n",
    "                                // 发送关闭请求到服务器\n",
    "                                const response = await fetch('/shutdown', {\n",
    "                                    method: 'POST',\n",
    "                                    headers: {\n",
    "                                        'Content-Type': 'application/json',\n",
    "                                    }\n",
    "                                });\n",
    "                                \n",
    "                                if (response.ok) {\n",
    "                                    document.body.innerHTML = `\n",
    "                                        <div style=\"display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-align: center; font-family: 'Microsoft YaHei';\">\n",
    "                                            <div>\n",
    "                                                <h1>系统已成功退出</h1>\n",
    "                                                <p style=\"font-size: 18px; margin: 20px 0;\">学习永无止境，期待下次再见！</p>\n",
    "                                                <p style=\"font-size: 14px; opacity: 0.8;\">您可以关闭此页面了</p>\n",
    "                                            </div>\n",
    "                                        </div>\n",
    "                                    `;\n",
    "                                }\n",
    "                            } catch (error) {\n",
    "                                document.body.innerHTML = `\n",
    "                                    <div style=\"display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-align: center; font-family: 'Microsoft YaHei';\">\n",
    "                                        <div>\n",
    "                                            <h1>无法自动退出</h1>\n",
    "                                            <p style=\"font-size: 18px; margin: 20px 0;\">请在命令行中按 Ctrl+C 停止服务</p>\n",
    "                                            <p style=\"font-size: 14px; opacity: 0.8;\">或者直接关闭此页面</p>\n",
    "                                        </div>\n",
    "                                    </div>\n",
    "                                `;\n",
    "                            }\n",
    "                        }\n",
    "                    }\n",
    "\n",
    "                    // 添加键盘快捷键 Ctrl+Q 退出\n",
    "                    document.addEventListener('keydown', function(e) {\n",
    "                        if (e.ctrlKey && e.key === 'q') {\n",
    "                            e.preventDefault();\n",
    "                            exitSystem();\n",
    "                        }\n",
    "                    });\n",
    "                </script>\n",
    "            </body>\n",
    "            </html>\n",
    "        '''\n",
    "\n",
    "        @self.app.route('/ask', methods=['POST'])\n",
    "        def ask_question():\n",
    "            data = request.get_json() or {}\n",
    "            question = data.get('question', '')\n",
    "            answer = self.core.ask_question(question)\n",
    "            return jsonify({'answer': answer})\n",
    "        \n",
    "        @self.app.route('/grade', methods=['POST'])\n",
    "        def grade_homework():\n",
    "            data = request.get_json() or {}\n",
    "            problem = data.get('problem', '')\n",
    "            answer = data.get('answer', '')\n",
    "            result = self.core.grade_homework(problem, answer)\n",
    "            return jsonify(result)\n",
    "        \n",
    "        @self.app.route('/timetable', methods=['GET'])\n",
    "        def get_timetable():\n",
    "            try:\n",
    "                timetable_data = self.core.query_timetable()\n",
    "                return jsonify({\n",
    "                    \"success\": True,\n",
    "                    \"data\": timetable_data\n",
    "                })\n",
    "            except Exception as e:\n",
    "                print(f\"获取课表接口失败: {e}\")\n",
    "                return jsonify({\n",
    "                    \"success\": False,\n",
    "                    \"message\": \"获取课表失败，请稍后再试\"\n",
    "                }), 500\n",
    "        \n",
    "        @self.app.route('/shutdown', methods=['POST'])\n",
    "        def shutdown():\n",
    "            # 获取werkzeug的关闭函数\n",
    "            func = request.environ.get('werkzeug.server.shutdown')\n",
    "            if func is None:\n",
    "                # 如果无法获取关闭函数，返回错误信息\n",
    "                return jsonify({'success': False, 'message': '无法停止服务器'})\n",
    "            \n",
    "            # 执行关闭\n",
    "            func()\n",
    "            return jsonify({'success': True, 'message': '服务器正在关闭...'})\n",
    "\n",
    "    def run(self, host='127.0.0.1', port=5000):\n",
    "        import webbrowser\n",
    "        import threading\n",
    "\n",
    "        print(f\"🎓 教育助手系统启动中...\")\n",
    "        print(f\"🌐 访问地址: http://{host}:{port}\")\n",
    "        print(f\"📱 功能包括：智能问答、作业批改、课程查询\")\n",
    "        \n",
    "        # 在新线程中延迟打开浏览器，确保服务器已启动\n",
    "        def open_browser():\n",
    "            import time\n",
    "            time.sleep(1)  # 等待1秒确保服务器启动\n",
    "            webbrowser.open_new_tab(f\"http://{host}:{port}\")\n",
    "\n",
    "        threading.Thread(target=open_browser, daemon=True).start()\n",
    "        \n",
    "        try:\n",
    "            self.app.run(host=host, port=port, debug=False, use_reloader=False, threaded=True)\n",
    "        except KeyboardInterrupt:\n",
    "            print(f\"\\n🚪 系统已正常退出，感谢使用！\")\n",
    "        except SystemExit:\n",
    "            print(f\"\\n🚪 系统已退出\")\n",
    "        except Exception as e:\n",
    "            print(f\"\\n❌ 系统异常退出：{e}\")\n",
    "        finally:\n",
    "            print(\"🔄 如需重新启动，请重新运行代码\")\n",
    "\n",
    "# ================== 执行入口 ==================\n",
    "if __name__ == \"__main__\":\n",
    "    interface = EduInterface()\n",
    "    interface.run()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
